import React, { useState, useEffect } from 'react';
import { api } from '../../request';
import './BackgroundConfig.css';
import { CircularProgress } from '@mui/material';
import { Delete, Refresh, CheckCircle } from '@mui/icons-material';

interface BackgroundConfigItem {
  id: number;
  config_type: 'header' | 'background';
  image_url: string;
  image_filename: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

const BackgroundConfig: React.FC = () => {
  const [configs, setConfigs] = useState<BackgroundConfigItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadType, setUploadType] = useState<'header' | 'background'>('header');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    loadConfigs();
  }, []);

  const loadConfigs = async () => {
    try {
      setLoading(true);
      const response = await api.admin.getBackgroundConfig();
      if (response.success) {
        setConfigs(response.data || []);
      } else {
        setMessage({ type: 'error', text: response.message || '获取配置失败' });
      }
    } catch (error) {
      console.error('获取背景配置失败:', error);
      setMessage({ type: 'error', text: '获取配置失败' });
    } finally {
      setLoading(false);
    }
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        setMessage({ type: 'error', text: '请选择图片文件' });
        return;
      }
      
      // 检查文件大小（限制为5MB）
      if (file.size > 5 * 1024 * 1024) {
        setMessage({ type: 'error', text: '文件大小不能超过5MB' });
        return;
      }

      setSelectedFile(file);
      
      // 创建预览URL
      const url = URL.createObjectURL(file);
      setPreviewUrl(url);
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      setMessage({ type: 'error', text: '请选择文件' });
      return;
    }

    try {
      setUploading(true);
      const response = await api.admin.uploadBackgroundImage(selectedFile, uploadType);
      
      if (response.success) {
        setMessage({ type: 'success', text: '上传成功' });
        setSelectedFile(null);
        setPreviewUrl('');
        // 重新加载配置
        await loadConfigs();
      } else {
        setMessage({ type: 'error', text: response.message || '上传失败' });
      }
    } catch (error) {
      console.error('上传失败:', error);
      setMessage({ type: 'error', text: '上传失败' });
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (configId: number) => {
    if (!window.confirm('确定要删除这个配置吗？')) {
      return;
    }

    try {
      const response = await api.admin.deleteBackgroundConfig(configId);
      
      if (response.success) {
        setMessage({ type: 'success', text: '删除成功' });
        await loadConfigs();
      } else {
        setMessage({ type: 'error', text: response.message || '删除失败' });
      }
    } catch (error) {
      console.error('删除失败:', error);
      setMessage({ type: 'error', text: '删除失败' });
    }
  };
  
  const handleActivate = async (configId: number) => {
    try {
      const response = await api.admin.activateBackgroundConfig(configId);
      
      if (response.success) {
        setMessage({ type: 'success', text: '配置已重新设置为当前使用' });
        await loadConfigs();
      } else {
        setMessage({ type: 'error', text: response.message || '设置失败' });
      }
    } catch (error) {
      console.error('设置失败:', error);
      setMessage({ type: 'error', text: '设置失败' });
    }
  };

  const clearMessage = () => {
    setMessage(null);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  const getConfigTypeName = (type: string) => {
    return type === 'header' ? 'Header背景' : '页面背景';
  };

  return (
    <div className="background-config">
      <div className="background-config-header">
        <h2>背景图片配置</h2>
        <p>管理客户端的Header背景图片和页面背景图片</p>
      </div>

      {message && (
        <div className={`message ${message.type}`}>
          <span>{message.text}</span>
          <button onClick={clearMessage} className="message-close">×</button>
        </div>
      )}

      <div className="upload-section">
        <h3>上传新背景图片</h3>
        
        <div className="upload-form">
          <div className="form-group-row">
            <div className="form-group">
              <label>配置类型：</label>
              <select 
                value={uploadType} 
                onChange={(e) => setUploadType(e.target.value as 'header' | 'background')}
                disabled={uploading}
                className="select-input"
              >
                <option value="header">Header背景</option>
                <option value="background">页面背景</option>
              </select>
            </div>

            <div className="form-group">
              <label>选择图片：</label>
              <div className="file-input-container">
                <input
                  type="file"
                  id="file-input"
                  accept="image/*"
                  onChange={handleFileSelect}
                  disabled={uploading}
                  className="file-input"
                />
                <label htmlFor="file-input" className="file-input-label">
                  {selectedFile ? selectedFile.name : '选择文件'}
                </label>
              </div>
            </div>
          </div>

          <div className="upload-preview-container">
            {previewUrl ? (
              <div className="preview-section">
                <h4>预览：</h4>
                <div className="preview-image-container">
                  <img src={previewUrl} alt="预览" className="preview-image" />
                  <div className="preview-type-badge">{uploadType === 'header' ? 'Header背景' : '页面背景'}</div>
                </div>
              </div>
            ) : (
              <div className="no-preview">
                <div className="no-preview-icon">📷</div>
                <p>选择图片后在此处预览</p>
              </div>
            )}
            
            <button 
              onClick={handleUpload} 
              disabled={!selectedFile || uploading}
              className="upload-btn"
            >
              {uploading ? (
                <>
                  <CircularProgress size={16} thickness={4} color="inherit" />
                  <span>上传中...</span>
                </>
              ) : (
                '上传图片'
              )}
            </button>
          </div>
        </div>
      </div>

      <div className="configs-section">
        <h3>当前配置</h3>
        
        {loading ? (
          <div className="loading">
            <CircularProgress size={40} thickness={4} />
            <p>正在加载配置...</p>
          </div>
        ) : (
          <div className="configs-list">
            {configs.length === 0 ? (
              <div className="empty-state">
                <i className="empty-icon">📷</i>
                <p>暂无背景配置，请上传新的背景图片</p>
              </div>
            ) : (
              configs.map((config) => (
                <div key={config.id} className={`config-item ${config.is_active ? 'active' : 'inactive'}`}>
                  <div className="config-image-container">
                    <div className="config-image">
                      <img src={config.image_url} alt={config.image_filename} />
                    </div>
                    {config.is_active && <div className="active-overlay">当前使用</div>}
                  </div>
                  
                  <div className="config-info">
                    <div className="config-type">
                      {getConfigTypeName(config.config_type)}
                      {config.is_active && <span className="active-badge">当前使用</span>}
                    </div>
                    <div className="config-filename">{config.image_filename}</div>
                    <div className="config-date">上传时间: {formatDate(config.created_at)}</div>
                  </div>
                  
                  <div className="config-actions">
                    {!config.is_active && (
                      <button 
                        onClick={() => handleActivate(config.id)}
                        className="activate-btn"
                        title="将此配置设为当前使用"
                      >
                        <Refresh fontSize="small" />
                        重新设置
                      </button>
                    )}
                    <button 
                      onClick={() => handleDelete(config.id)}
                      className="delete-btn"
                      title="删除此背景配置"
                    >
                      <Delete fontSize="small" />
                      删除
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default BackgroundConfig;